#include "private_mqtt_publish_msg.h"
#include "cJSON.h"
#include "cJSON_static_mem.h"
#include "print_rtt.h"
#include <math.h>
uint64_t publish_id;
void compare_with_message2_1800_181B_status(Message2 *message2, Modbus_AllData *swap_all_data)
{

  uint8_t need_update = 0;           // 标记是否需要更新
  const float FLOAT_EPSILON = 0.01f; // 浮点数比较容差（精度0.01时足够）

  // 1. 输入电压 vol (0x1804~0x1805)
  if (fabsf(message2->vol - swap_all_data->run_status.input_volt_1) > FLOAT_EPSILON)
  {
    message2->vol = swap_all_data->run_status.input_volt_1;
    need_update = 1;
  }

  // 2. 空开电流 cur (0x1806~0x1807)
  if (fabsf(message2->cur - swap_all_data->run_status.air_switch_current_1) > FLOAT_EPSILON)
  {
    message2->cur = swap_all_data->run_status.air_switch_current_1;
    need_update = 1;
  }

  // 3. 空开功率 pow (0x1808~0x1809)
  if (fabsf(message2->pow - swap_all_data->run_status.air_switch_power) > FLOAT_EPSILON)
  {
    message2->pow = swap_all_data->run_status.air_switch_power;
    need_update = 1;
  }

  // 4. 输出电量 out_ene (0x180E~0x180F)
  if (fabsf(message2->out_ene - swap_all_data->run_status.output_energy) > FLOAT_EPSILON)
  {
    message2->out_ene = swap_all_data->run_status.output_energy;
    need_update = 1;
  }

  // 5. 端口温度 T1 (0x1818)
  float new_T1 = (float)swap_all_data->run_status.port_temp;
  if (fabsf(message2->T1 - new_T1) > FLOAT_EPSILON)
  {
    message2->T1 = new_T1;
    need_update = 1;
  }

  // 6. 板载温度 T2 (0x1819)
  float new_T2 = (float)swap_all_data->run_status.board_temp;
  if (fabsf(message2->T2 - new_T2) > FLOAT_EPSILON)
  {
    message2->T2 = new_T2;
    need_update = 1;
  }

  // 7. 强制在线（你原有逻辑）
  if (!message2->online)
  {
    message2->online = 1;
    need_update = 1;
  }

  // 8. 如果有任何更新，设置标志位
  if (need_update)
  {
    message2->need_updata_flag = 1;
  }
}
void compare_with_message2_1824_1828_status(Message2 *message2, Modbus_AllData *swap_all_data)
{
  uint8_t need_update = 0;
  const float FLOAT_EPSILON = 0.01f;

  // 1. 运行状态字 run_status_word (0x1824) → 可用于解析 sta 状态
  // 假设 bit0 表示开关状态：0=合闸(开), 1=分闸(关)
  uint8_t new_sta = 0; // = swap_all_data->run_status.run_status_word & 0x01) ? 1 : 0;
  if (BITTST(swap_all_data->run_status.run_status_word, 5))
  {
    new_sta = 0;
  }
  if (BITTST(swap_all_data->run_status.run_status_word, 7))
  {
    new_sta = 1;
  }
  if (message2->sta != new_sta)
  {
    message2->sta = new_sta;
    need_update = 1;
  }

  // 2. 报警状态字 alarm_word1, alarm_word2 (0x1825~0x1826)
  // 当前 Message2 不包含报警字段，可忽略或扩展结构体

  // 3. 输入电量（放电1）input_energy_discharge_1 (0x1827~0x1828)
  if (fabsf(message2->in_ene - swap_all_data->run_status.input_energy_discharge_1) > FLOAT_EPSILON)
  {
    message2->in_ene = swap_all_data->run_status.input_energy_discharge_1;
    need_update = 1;
  }

  // 4. 更新标志
  if (need_update)
  {
    message2->need_updata_flag = 1;
  }
}
/**
 * @brief 比较 Message2 与 Modbus 运行状态数据（0x18A4~0x18B5），若不一致则更新并置更新标志
 * @param message2 指向 Message2 结构体的指针
 * @param swap_all_data 指向 Modbus_AllData 结构体的指针
 */
void compare_with_message2_18A4_18B5_status(Message2 *message2, Modbus_AllData *swap_all_data)
{
  uint8_t need_update = 0;
  const float FLOAT_EPSILON = 0.005f;

  // 1. 输入电压2 input_volt_2 (0x18A4~0x18A5) → 单位 V × 100
  float new_vol2 = (float)swap_all_data->run_status.input_volt_2 / 100.0f;
  if (fabsf(message2->vol - new_vol2) > FLOAT_EPSILON)
  {
    message2->vol = new_vol2;
    need_update = 1;
  }

  // 2. 空开电流2 air_switch_current_2 (0x18A6~0x18A7) → 单位 A × 100
  float new_cur2 = (float)swap_all_data->run_status.air_switch_current_2 / 100.0f;
  if (fabsf(message2->cur - new_cur2) > FLOAT_EPSILON)
  {
    message2->cur = new_cur2;
    need_update = 1;
  }

  // 3. 累计电量 total_energy (0x18A8~0x18A9) → Y*0.01 kWh
  float new_total_energy = (float)(swap_all_data->run_status.total_energy / 100.0f);
  if (fabsf(message2->curMonthEnergy - new_total_energy) > FLOAT_EPSILON)
  {
    message2->curMonthEnergy = new_total_energy;
    need_update = 1;
  }

  // 4. 输入电量（放电2）input_energy_discharge_2 (0x18AA~0x18AB) → Y*0.01 kWh
  float input_energy2 = (float)(swap_all_data->run_status.input_energy_discharge_2 / 100.0f);
  if (fabsf(message2->in_ene - (input_energy2)) > FLOAT_EPSILON)
  {
    message2->in_ene = input_energy2;
    need_update = 1;
  }

  // 5. 输出电量2 output_energy_2 (0x18AC~0x18AD) → Y*0.01 kWh
  float output_energy2 = (float)(swap_all_data->run_status.output_energy_2 / 100.0f);
  if (fabsf(message2->out_ene - (output_energy2)) > FLOAT_EPSILON)
  {
    message2->out_ene = output_energy2;
    need_update = 1;
  }

  // 6. 报警/状态字（0x18AE~0x18B0）→ 当前 Message2 未使用，可忽略

  // 7. 母排计量电压2 bus_meter_volt_2 (0x18B4~0x18B5) → 单位 V × 100（未映射到 Message2）

  // 8. 更新标志
  if (need_update)
  {
    message2->need_updata_flag = 1;
  }
}
void publish_message2_status(uint64_t id, uint8_t box, Message2 *message2)
{
  //  char topic[128];
  char *json_str = NULL;
  int32_t topic_len;
  char fw_version[7] = {0};
  size_t mark = cJSON_StaticMem_TakeMark(); // ① 打标记
  cJSON *root = NULL;
  struct tm *timeinfo;
  char time_str[20];
  uint64_t t;
#ifdef MQTT_CLIENT_DEBUG
  LOG_COLOR(YELLOW, "CJSON_MARK : %d\n", mark);
#endif

  // --- 1. 构造主题：/v1/device/me/telemetry/<channel_index> ---
  // 如果将来 deviceName 是变量，可替换 "device"
  topic_len = snprintf(mqtt_publish_msg_push_to_queue->publish_topic, sizeof(mqtt_publish_msg_push_to_queue->publish_topic), "/v1/device/me/telemetry/%d", box);
  if (topic_len >= sizeof(mqtt_publish_msg_push_to_queue->publish_topic) || mqtt_publish_msg_push_to_queue->publish_topic < 0)
  {
#ifdef MQTT_CLIENT_DEBUG
    LOG_ERROR("[ERROR] Topic string too long or error\n");
#endif
    goto CLEAN_AND_EXIT;
  }

#ifdef MQTT_CLIENT_DEBUG
  LOG_INFO("[INFO] Publishing Message2 to topic: %s (QoS=1)\n", mqtt_publish_msg_push_to_queue->publish_topic);
#endif

  // --- 2. 创建 cJSON 对象 ---
  root = cJSON_CreateObject();
  if (root == NULL)
  {
#ifdef MQTT_CLIENT_DEBUG
    LOG_ERROR("[ERROR] Failed to create cJSON object\n");
#endif
    goto CLEAN_AND_EXIT;
  }

  // --- 3. 填充 Message2 数据 ---
  cJSON_AddNumberToObject(root, "id", id);       // 报文编号
  cJSON_AddNumberToObject(root, "channel", box); // 通道号
  if (message2->online == 0)
  {
    cJSON_AddNumberToObject(root, "online", 0);
  }
  else
  {
    cJSON_AddNumberToObject(root, "online", message2->online);
    cJSON_AddNumberToObject(root, "vol", message2->vol);
    cJSON_AddNumberToObject(root, "cur", message2->cur);
    cJSON_AddNumberToObject(root, "pow", message2->pow);
    cJSON_AddNumberToObject(root, "curMonthEnergy", message2->curMonthEnergy);
    cJSON_AddNumberToObject(root, "lastMonthEnergy", message2->lastMonthEnergy);
    cJSON_AddNumberToObject(root, "portTemp", message2->T1);  // 端口温度
    cJSON_AddNumberToObject(root, "boardTemp", message2->T2); // 板载温度
    cJSON_AddNumberToObject(root, "in_ene", message2->in_ene);
    cJSON_AddNumberToObject(root, "out_ene", message2->out_ene);
    cJSON_AddNumberToObject(root, "sta", message2->sta); // 开关状态
    cJSON_AddNumberToObject(root, "authState", message2->authState ? 1 : 0);
  }
  // --- 4. 格式化时间戳为 "YYYY-MM-DD HH:MM:SS" ---

  t = message2->last_send_time;
  // 假设 last_send_time 是 Unix 时间戳（单位：秒）
  // 如果是毫秒，请先除以 1000

  timeinfo = localtime((const time_t *)&t);
  strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", timeinfo);
  cJSON_AddStringToObject(root, "dataTime", time_str);
  // --- 5. 添加版本号 ---
  memcpy(fw_version, (char *)0x800C314, 5);

  cJSON_AddStringToObject(root, "current_fw_version", fw_version);

  // --- 6. 生成紧凑 JSON 字符串 ---
  json_str = cJSON_PrintUnformatted(root);
  if (json_str == NULL)
  {
#ifdef MQTT_CLIENT_DEBUG
    LOG_ERROR("[ERROR] Failed to print JSON\n");
#endif
    goto CLEAN_AND_EXIT;
  }

#ifdef MQTT_CLIENT_DEBUG
  LOG_INFO("[INFO] Payload: %s\n", json_str);
#endif
  memcpy(mqtt_publish_msg_push_to_queue->msg, json_str, strlen(json_str));
  mqtt_publish_msg_push_to_queue->msg_lenth = strlen(json_str);
  if (xQueueSend(xPublishTopicMsgQueueHandle, mqtt_publish_msg_push_to_queue->publish_topic, 0U) == pdPASS)
  {
    LOG_INFO("send queue data success!\r\n");
  }
  else
  {
    LOG_ERROR("send queue data failed!\r\n");
  }
CLEAN_AND_EXIT:
#ifdef MQTT_CLIENT_DEBUG
  LOG_COLOR(YELLOW, "rollback CJSON_MARK : %d\n", mark);
#endif
  cJSON_StaticMem_Rollback(mark); // 自动释放 cJSON 和 json_str
}

/**
 * @brief 比较并更新 Message1 中 0x3000~0x3009 寄存器对应的参数
 * @param message1 指向 Message1 结构体的指针
 * @param swap_all_data 指向 Modbus_AllData 结构体的指针
 */
void compare_with_message1_3000_3009_status(Message1 *message1, Modbus_AllData *swap_all_data)
{
  uint8_t need_update = 0;

  // 1. 过压保护使能 (0x3001)
  uint8_t new_over_volt_en = 0; // 默认值
  switch (swap_all_data->user_param.over_volt_en)
  {
  case 0x00AA: // 启用（报警+跳闸）
    new_over_volt_en = 0;
    break;
  case 0x00BB: // 仅报警
    new_over_volt_en = 1;
    break;
  case 0x0000: // 禁用
  default:
    new_over_volt_en = 2;
    break;
  }
  if (message1->overVoltEn != new_over_volt_en)
  {
    message1->overVoltEn = new_over_volt_en;
    need_update = 1;
  }

  // 2. 过压保护阈值 (0x3002)，单位 V，范围 50~80
  uint8_t new_over_volt_val = (uint8_t)swap_all_data->user_param.over_volt_thr;
  if (new_over_volt_val >= 50 && new_over_volt_val <= 80)
  {
    if (message1->overVoltVal != new_over_volt_val)
    {
      message1->overVoltVal = new_over_volt_val;
      need_update = 1;
    }
  }

  // 3. 过压保护延时 (0x3005)，单位 100ms → 转为秒
  uint8_t new_over_volt_delay = (uint8_t)(swap_all_data->user_param.over_volt_delay / 10); // 10个100ms = 1秒
  if (new_over_volt_delay >= 1 && new_over_volt_delay <= 60)
  {
    if (message1->overVoltDelay != new_over_volt_delay)
    {
      message1->overVoltDelay = new_over_volt_delay;
      need_update = 1;
    }
  }

  // 4. 欠压保护使能 (0x3007)
  uint8_t new_under_volt_en = 0;
  switch (swap_all_data->user_param.under_volt_en)
  {
  case 0x00AA:
    new_under_volt_en = 0;
    break;
  case 0x00BB:
    new_under_volt_en = 1;
    break;
  case 0x0000:
  default:
    new_under_volt_en = 2;
    break;
  }
  if (message1->underVoltEn != new_under_volt_en)
  {
    message1->underVoltEn = new_under_volt_en;
    need_update = 1;
  }

  // 5. 欠压保护阈值 (0x3008)，单位 V，范围 35~49
  uint8_t new_under_volt_val = (uint8_t)swap_all_data->user_param.under_volt_thr;
  if (new_under_volt_val >= 35 && new_under_volt_val <= 49)
  {
    if (message1->underVoltVal != new_under_volt_val)
    {
      message1->underVoltVal = new_under_volt_val;
      need_update = 1;
    }
  }

  // 6. 欠压保护延时 (0x3009)，单位 100ms → 转为秒
  uint8_t new_under_volt_delay = (uint8_t)(swap_all_data->user_param.under_volt_delay / 10);
  if (new_under_volt_delay >= 1 && new_under_volt_delay <= 60)
  {
    if (message1->underVoltDelay != new_under_volt_delay)
    {
      message1->underVoltDelay = new_under_volt_delay;
      need_update = 1;
    }
  }

  // --- 设置更新标志 ---
  if (need_update)
  {
    message1->need_updata_flag = 1;
  }
}
/**
 * @brief 比较并更新 Message1 中 0x3016~0x301E 寄存器对应的温度保护参数
 * @param message1 指向 Message1 结构体的指针
 * @param swap_all_data 指向 Modbus_AllData 结构体的指针
 */
void compare_with_message1_3016_301E_status(Message1 *message1, Modbus_AllData *swap_all_data)
{
  uint8_t need_update = 0;

  // ========== 端口温度保护 ==========

  // 1. 端口过温保护使能 (0x3016)
  uint8_t new_port_temp_en = 2; // 默认禁用
  switch (swap_all_data->user_param.port_ot_en)
  {
  case 0x00AA: // 启用（跳闸+报警）
    new_port_temp_en = 0;
    break;
  case 0x00BB: // 仅报警
    new_port_temp_en = 1;
    break;
  case 0x0000: // 禁用
    new_port_temp_en = 2;
    break;
  }
  if (message1->portTempEn != new_port_temp_en)
  {
    message1->portTempEn = new_port_temp_en;
    need_update = 1;
  }

  // 2. 端口过温保护阈值 (0x3017)，单位 ℃，范围 70~130
  uint8_t new_port_temp_val = (uint8_t)swap_all_data->user_param.port_ot_thr;
  if (new_port_temp_val >= 70 && new_port_temp_val <= 130)
  {
    if (message1->portTempVal != new_port_temp_val)
    {
      message1->portTempVal = new_port_temp_val;
      need_update = 1;
    }
  }

  // 3. 端口过温保护延时 (0x3018)，单位 100ms → 转为秒
  uint8_t new_port_temp_delay = (uint8_t)(swap_all_data->user_param.port_ot_delay / 10); // 转为秒
  if (new_port_temp_delay >= 1 && new_port_temp_delay <= 60)
  {
    if (message1->portTempDelay != new_port_temp_delay)
    {
      message1->portTempDelay = new_port_temp_delay;
      need_update = 1;
    }
  }

  // ========== 板载温度保护 ==========

  // 4. 板载过温保护使能 (0x301C)
  uint8_t new_board_temp_en = 2;
  switch (swap_all_data->user_param.board_ot_en)
  {
  case 0x00AA:
    new_board_temp_en = 0;
    break;
  case 0x00BB:
    new_board_temp_en = 1;
    break;
  case 0x0000:
    new_board_temp_en = 2;
    break;
  }
  if (message1->boardTempEn != new_board_temp_en)
  {
    message1->boardTempEn = new_board_temp_en;
    need_update = 1;
  }

  // 5. 板载过温保护阈值 (0x301D)，单位 ℃，范围 70~100
  uint8_t new_board_temp_val = (uint8_t)swap_all_data->user_param.board_ot_thr;
  if (new_board_temp_val >= 70 && new_board_temp_val <= 100)
  {
    if (message1->boardTempVal != new_board_temp_val)
    {
      message1->boardTempVal = new_board_temp_val;
      need_update = 1;
    }
  }

  // 6. 板载过温保护延时 (0x301E)，单位 100ms → 转为秒
  uint8_t new_board_temp_delay = (uint8_t)(swap_all_data->user_param.board_ot_delay / 10);
  if (new_board_temp_delay >= 1 && new_board_temp_delay <= 60)
  {
    if (message1->boardTempDelay != new_board_temp_delay)
    {
      message1->boardTempDelay = new_board_temp_delay;
      need_update = 1;
    }
  }

  // ========== 更新标志位 ==========
  if (need_update)
  {
    message1->need_updata_flag = 1;
  }
}
/**
 * @brief 比较并更新 Message1 中 0x302E~0x3036 寄存器对应的自动重合闸参数
 * @param message1 指向 Message1 结构体的指针
 * @param swap_all_data 指向 Modbus_AllData 结构体的指针
 */
void compare_with_message1_302E_3036_status(Message1 *message1, Modbus_AllData *swap_all_data)
{
  uint8_t need_update = 0;

  // ========== 过流自动重合使能 (0x3031) ==========
  // 0x00AA = 启用, 其他 = 禁用
  uint8_t new_over_cur_re_en = (swap_all_data->user_param.over_current_reclose_en == 0x00AA) ? 0 : 1;
  if (message1->overCurReEn != new_over_cur_re_en)
  {
    message1->overCurReEn = new_over_cur_re_en;
    need_update = 1;
  }

  // ========== 过流重合延时 (0x3032)：单位 100ms → 转为秒 ==========
  uint8_t new_over_cur_re_delay = (uint8_t)(swap_all_data->user_param.over_current_reclose_delay / 10); // 10个100ms = 1秒
  if (new_over_cur_re_delay >= 1 && new_over_cur_re_delay <= 60)
  {
    if (message1->overCurReDelay != new_over_cur_re_delay)
    {
      message1->overCurReDelay = new_over_cur_re_delay;
      need_update = 1;
    }
  }

  // ========== 过流重合次数 (0x3033)：1~5 ==========
  uint8_t new_over_cur_re_cnt = (uint8_t)swap_all_data->user_param.over_current_reclose_cnt;
  if (new_over_cur_re_cnt >= 1 && new_over_cur_re_cnt <= 5)
  {
    if (message1->overCurReCnt != new_over_cur_re_cnt)
    {
      message1->overCurReCnt = new_over_cur_re_cnt;
      need_update = 1;
    }
  }

  // ========== 电压恢复回差值 (0x3030)：1~10V，但 Message1 无字段，跳过 ==========
  // 若未来扩展 Message1，可添加 volt_recover_hyst 字段

  // ========== 过压/欠压自恢复使能 (0x302E, 0x302F)：Message1 无对应字段，跳过 ==========
  // 当前结构体无法表示，建议扩展：
  // uint8_t volt_auto_recover_en;  // 0:启用, 1:禁用

  // ========== 更新标志位 ==========
  if (need_update)
  {
    message1->need_updata_flag = 1;
  }
}
void publish_message1_status(uint64_t id, uint8_t box, Message1 *message1)
{
  char *json_str = NULL;
  int32_t topic_len;
  size_t mark = cJSON_StaticMem_TakeMark(); // ① 打标记
  cJSON *root = NULL;
  struct tm *timeinfo;
  char time_str[20];
  uint64_t t;
  size_t json_len;

#ifdef MQTT_CLIENT_DEBUG
  LOG_COLOR(YELLOW, "CJSON_MARK : %d\n", mark);
#endif

  // --- 1. 构造主题：/v1/device/me/setpoint/<channel_index> ---
  topic_len = snprintf(mqtt_publish_msg_push_to_queue->publish_topic,
                       sizeof(mqtt_publish_msg_push_to_queue->publish_topic),
                       "/v1/device/me/setpoint/%d", box);
  if (topic_len < 0 || topic_len >= sizeof(mqtt_publish_msg_push_to_queue->publish_topic))
  {
#ifdef MQTT_CLIENT_DEBUG
    LOG_ERROR("[ERROR] Topic string too long or error\n");
#endif
    goto CLEAN_AND_EXIT;
  }

#ifdef MQTT_CLIENT_DEBUG
  LOG_INFO("[INFO] Publishing Message1 to topic: %s (QoS=1)\n", mqtt_publish_msg_push_to_queue->publish_topic);
#endif

  // --- 2. 创建 cJSON 对象 ---
  root = cJSON_CreateObject();
  if (root == NULL)
  {
#ifdef MQTT_CLIENT_DEBUG
    LOG_ERROR("[ERROR] Failed to create cJSON object\n");
#endif
    goto CLEAN_AND_EXIT;
  }

  // --- 3. 填充 Message1 数据 ---
  cJSON_AddNumberToObject(root, "id", id);
  cJSON_AddNumberToObject(root, "channel", box);
  cJSON_AddNumberToObject(root, "workMode", message1->workMode);
  cJSON_AddNumberToObject(root, "overVoltEn", message1->overVoltEn);
  cJSON_AddNumberToObject(root, "overVoltVal", message1->overVoltVal);
  cJSON_AddNumberToObject(root, "overVoltDelay", message1->overVoltDelay);
  cJSON_AddNumberToObject(root, "underVoltEn", message1->underVoltEn);
  cJSON_AddNumberToObject(root, "underVoltVal", message1->underVoltVal);
  cJSON_AddNumberToObject(root, "underVoltDelay", message1->underVoltDelay);

  // --- voltRecoverDiff 字段处理 ---
  // 如果你的 Message1 结构体中没有此字段，请注释或替换为默认值
#ifdef HAS_VOLT_RECOVER_DIFF
  cJSON_AddNumberToObject(root, "voltRecoverDiff", message1->voltRecoverDiff);
#else
  cJSON_AddNumberToObject(root, "voltRecoverDiff", 2); // 默认值，或从 Modbus 读取
#endif

  cJSON_AddNumberToObject(root, "overCurEn", message1->overCurEn);
  cJSON_AddNumberToObject(root, "overCurVal", message1->overCurVal);
  //   cJSON_AddNumberToObject(root, "overCurDelay", message1->overCurDelay);
  cJSON_AddNumberToObject(root, "overCurReEn", message1->overCurReEn);
  cJSON_AddNumberToObject(root, "overCurReCnt", message1->overCurReCnt);
  cJSON_AddNumberToObject(root, "overCurReDelay", message1->overCurReDelay);
  cJSON_AddNumberToObject(root, "portTempEn", message1->portTempEn);
  cJSON_AddNumberToObject(root, "portTempVal", message1->portTempVal);
  cJSON_AddNumberToObject(root, "portTempDelay", message1->portTempDelay);
  cJSON_AddNumberToObject(root, "boardTempEn", message1->boardTempEn);
  cJSON_AddNumberToObject(root, "boardTempVal", message1->boardTempVal);
  cJSON_AddNumberToObject(root, "boardTempDelay", message1->boardTempDelay);
  cJSON_AddStringToObject(root, "energySettleTime", message1->energySettleTime);

  // --- 4. 格式化时间戳为 "YYYY-MM-DD HH:MM:SS" ---
  t = message1->last_send_time;
  timeinfo = localtime((const time_t *)&t);
  strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", timeinfo);
  cJSON_AddStringToObject(root, "dataTime", time_str);

  // --- 5. 生成紧凑 JSON 字符串 ---
  json_str = cJSON_PrintUnformatted(root);
  if (json_str == NULL)
  {
#ifdef MQTT_CLIENT_DEBUG
    LOG_ERROR("[ERROR] Failed to print JSON\n");
#endif
    goto CLEAN_AND_EXIT;
  }

#ifdef MQTT_CLIENT_DEBUG
  LOG_INFO("[INFO] Payload: %s\n", json_str);
#endif

  // --- 6. 复制到队列缓冲区 ---
  json_len = strlen(json_str);
  if (json_len >= sizeof(mqtt_publish_msg_push_to_queue->msg))
  {
    LOG_ERROR("[ERROR] JSON payload too large for buffer\n");
    goto CLEAN_AND_EXIT;
  }
  memcpy(mqtt_publish_msg_push_to_queue->msg, json_str, json_len);
  mqtt_publish_msg_push_to_queue->msg_lenth = json_len;

  // --- 7. 发送到发布队列 ---
  if (xQueueSend(xPublishTopicMsgQueueHandle, mqtt_publish_msg_push_to_queue->publish_topic, 0U) == pdPASS)
  {
    LOG_INFO("send queue data success!\r\n");
  }
  else
  {
    LOG_ERROR("send queue data failed!\r\n");
  }

CLEAN_AND_EXIT:
#ifdef MQTT_CLIENT_DEBUG
  LOG_COLOR(YELLOW, "rollback CJSON_MARK : %d\n", mark);
#endif
  cJSON_StaticMem_Rollback(mark); // 自动释放 root 和 json_str
}
